//
//  YXWWeatherData.m
//  ObserverPattern
//
//  Created by ying on 2016/12/13.
//  Copyright © 2016年 ying. All rights reserved.
//

#import "YXWWeatherData.h"

struct {
    unsigned int didUpdateData : 1;
}_delegateFlags;

@interface YXWWeatherData ()

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation YXWWeatherData

static YXWWeatherData *data;

+ (instancetype)sharedWeatherDataSDK{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        data = [[YXWWeatherData alloc] init];
    });
    return data;
}

- (void)setDelegate:(id<YXWWeatherDataDelegate>)delegate{
    _delegate = delegate;
    _delegateFlags.didUpdateData = [_delegate respondsToSelector:@selector(updateTemperature:humidity:andPressure:)];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(performDelegate) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

- (void)performDelegate{
    if (_delegateFlags.didUpdateData) {
        int a = 100;
        int b = 1;
        float tpure = (rand() % (b-a))+ a;
        float hmty = (rand() % (b-a))+ a;;
        float psure = (rand() % (b-a))+ a;;
        [self.delegate updateTemperature:tpure humidity:hmty andPressure:psure];
    }
}

- (void)dealloc{
    [self.timer invalidate];
    self.timer = nil;
}

@end
